package com.example.dormitorymanagement.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.dormitorymanagement.entity.Administrator;
import com.example.dormitorymanagement.entity.Admin;
import com.example.dormitorymanagement.exception.AbnormalPermissions;
import com.example.dormitorymanagement.mapper.AdministratorMapper;
import com.example.dormitorymanagement.service.impl.AdministratorServiceImpl;
import io.swagger.annotations.*;
import org.apache.catalina.session.StandardSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author admin
 * @since 2021-06-06
 */
//@CrossOrigin
@RestController
@RequestMapping("/admin")
@Api(tags = "管理员，该模块，权限高的可以进行任何操作，权限低的只能进行登录和退出")
public class AdministratorController {

    @Autowired
    private AdministratorServiceImpl administratorServiceimpl;

    @Autowired
    private AdministratorMapper administratorMapper;

    @Autowired
    private com.example.dormitorymanagement.service.impl.suthorityservice suthorityservice;

    @PostMapping(value = "/addormodify")
    @ApiOperation(value = "管理员的添加或者修改")
    public Map<String, Object> addormodify(@RequestBody Administrator administrator,HttpServletRequest request) throws AbnormalPermissions {

       Map<String, Object> map = suthorityservice.verification(request);

        if (map.size() != 0)
        {
            return map;
        }

        QueryWrapper<Administrator> queryWrapper = new QueryWrapper<>();

        if (administrator.getId() != null && administrator.getId() != 0)//id不为空就是进行修改
        {
            queryWrapper.eq("username", administrator.getUsername());

            Integer integer = administratorMapper.selectCount(queryWrapper);

            if (integer != 0)
            {
                map.put("stat",false);

                map.put("message","更新失败，已存在该数据");

                return map;
            }

            if (administratorServiceimpl.updateById(administrator)) {

                map.put("stat",true);

                map.put("message","更新成功，本次更新的数据：" + administrator);

            }else {

                map.put("stat",false);

                map.put("message","更新失败");

            }

            return map;
        }

        //添加管理员前，先查看一下数据库中是否有该管理员
        queryWrapper.clear();

        queryWrapper.eq("username", administrator.getUsername());

        Integer integer = administratorMapper.selectCount(queryWrapper);

        if (integer == 0) {

            administrator.setAuthority("低");

            boolean save = administratorServiceimpl.save(administrator);

            if (save) {

                map.put("stat", true);

                map.put("message", "添加成功");
                return map;
            }

            map.put("stat", false);

            map.put("message", "添加失败，请联系管理员");
            return map;
        }

        map.put("stat", false);

        map.put("message", "添加失败，已存在该管理员");

        return map;

    }

    @GetMapping(value = "/deleteadmin")
    @ApiOperation(value = "通过id来删除对应权限低的管理员，权限高的无法删除")
    public Map<String,Object> deleteadmin(@ApiParam(name = "id",value = "通过id删除对应的数据",required = true) @RequestParam(value = "id") Integer id,HttpServletRequest request) throws AbnormalPermissions {

        Map<String, Object> map = suthorityservice.verification(request);

        if (map.size() != 0)
        {
            return map;
        }

        UpdateWrapper<Administrator> administratorUpdateWrapper = new UpdateWrapper<>();

        administratorUpdateWrapper.eq("id",id);

        Administrator administrator = administratorMapper.selectOne(administratorUpdateWrapper);

        if (administrator.getAuthority().contains("高"))
        {
            map.put("stat",true);

            map.put("message","无法删除权限为高的管理员");

            return map;
        }

        int delete = administratorMapper.delete(administratorUpdateWrapper);

        if (delete == 1)
        {
            map.put("stat",true);

            map.put("message","删除成功");

            return map;
        }

        map.put("stat",false);

        map.put("message","删除失败，请联系管理员");

        return map;

    }

    @GetMapping(value = "/getadministrator")
    @ApiOperation(value = "通过条件来获取用户表中的所有数据，一页10条数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authority",value = "根据权限的高或者低来查找数据",dataType = "String",required = false),
            @ApiImplicitParam(name = "pc",value = "第几页，不传值默认为第一页",dataType = "int"),
    })
    public Map<String, Object> getadministrator(String authority, Integer pc,HttpServletRequest request) throws AbnormalPermissions {

        Map<String, Object> map = suthorityservice.verification(request);

        if (map.size() != 0)
        {
            return map;
        }
        if (pc == null)
        {
            pc = 1;
        }

        QueryWrapper<Administrator> administratorQueryWrapper = new QueryWrapper<>();

        map.put("authority",authority);

        administratorQueryWrapper.allEq(map,false).orderByDesc("id");

        map.clear();

        Page<Administrator> administratorPage = new Page<>(pc,10);

        administratorMapper.selectPage(administratorPage,administratorQueryWrapper);

        if ( pc > administratorPage.getPages())
        {
            map.put("stat",false);

            map.put("message","页数越界，总页数：" + administratorPage.getPages() + "，当前页数:" + administratorPage.getCurrent());

            return map;
        }

        List<Administrator> administrators = administratorPage.getRecords();

        map.put("stat",true);
        map.put("services", administrators);
        map.put("pages",administratorPage.getPages());
        map.put("page",administratorPage.getCurrent());
        map.put("total", administratorPage.getTotal());
        map.put("current", administratorPage.getCurrent());
        map.put("hasPrevious",administratorPage.hasPrevious());
        map.put("hasNext",administratorPage.hasNext());
        return map;

    }

    @GetMapping(value = "/logon")
    @ApiOperation(value = "管理员用户登录")
    public Map<String,Object> logon(String username,String password,HttpServletRequest request)
    {
        Map<String,Object> map = new HashMap<>();

        QueryWrapper<Administrator> administratorQueryWrapper = new QueryWrapper<>();

        administratorQueryWrapper.eq("username",username);

        Integer integer = administratorMapper.selectCount(administratorQueryWrapper);

        if (integer == 0)
        {
            map.put("stat",false);

            map.put("message","该用户不存在");

            return map;
        }

        administratorQueryWrapper.eq("password",password);

        integer = administratorMapper.selectCount(administratorQueryWrapper);

        if (integer == 0)
        {
            map.put("stat",false);

            map.put("message","密码错误");

            return map;
        }

        Administrator administrator = administratorMapper.selectOne(administratorQueryWrapper);

        administrator.setPassword(null);

        HttpSession session = request.getSession();

        session.setAttribute("username",administrator.getUsername());
        session.setAttribute("name",administrator.getName());
        session.setAttribute("authority",administrator.getAuthority());

        map.put("stat",true);

        map.put("message","登录成功");

        map.put("administrator",administrator);

        return map;

    }

    @GetMapping(value = "/dropout")
    @ApiOperation(value = "用户退出，成功返回true，失败返false")
    public boolean dropout(HttpServletRequest request)
    {
        HttpSession session = request.getSession();

        session.removeAttribute("username");

        session.removeAttribute("name");

        session.removeAttribute("authority");
        System.out.println("退出登录");
        return true;
    }

    
}

